<?php
function http_request($url,$data = null,$headers=array()){
    $curl = curl_init();
    if( count($headers) >= 1 ){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_URL, $url);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}
function downpic($url){

$file = file_get_contents($url);
$pic_local_path = './Public/uploads/wallhaven/';
$arr = parse_url($url);
$arr2 = pathinfo($arr['path']);
$filename=$arr2['basename'];
$pic_local = $pic_local_path . $filename;
return file_put_contents($pic_local, $file);
}

function downpics($url){

import("ORG.Net.Http");
$http=new \Org\Net\Http;

$arr = parse_url($url);
$arr2 = pathinfo($arr['path']);
$filename=$arr2['basename'];

$http->download($url,$filename);

}

/**
 * 下载远程文件
 * @param  string  $url     网址
 * @param  string  $filename    保存文件名
 * @param  integer $timeout 过期时间
 * return boolean|string
 */
//$res = http_down($value['path'],$small,$value['purity']);
function http_down($url,$small,$purity,$timeout = 60) {
    $path = './Public/uploads/wallhaven/'.$purity.'/';

    // if (!is_dir($path) && !mkdir($path, 0755, true)) {
    //     return false;
    // }
    $arr = parse_url($url);
    $arr2 = pathinfo($arr['path']);
    $filename=$arr2['basename'];

    $fp = fopen($path.$filename, 'w');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);


//
    $pathsmall = './Public/uploads/wallhaven/small/'.$purity.'/';
////     if (!is_dir($pathsmall) && !mkdir($pathsmall, 0755, true)) {
////         return false;
////     }
///

    $arrsmall = parse_url($small);
//
    $arrsmall2 = pathinfo($arrsmall['path']);
    $filenamesmall=$arrsmall2['basename'];
//
    $fpsmall = fopen($pathsmall.$filenamesmall, 'w');
    $chsmall = curl_init($small);
    curl_setopt($chsmall, CURLOPT_FILE, $fpsmall);
    curl_setopt($chsmall, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($chsmall, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($chsmall, CURLOPT_SSL_VERIFYHOST, false);
    curl_exec($chsmall);
    curl_close($chsmall);
    fclose($fpsmall);
    $file['larger']=$filename;
    $file['small']=$filenamesmall;

    return $file;
}